package cn.elricyu.tt.ui.comp;

import org.apache.log4j.Appender;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Text;

import cn.elricyu.tt.bean.User;
import cn.elricyu.tt.store.SystemContainer;
import cn.elricyu.tt.store.CurrentContext;
import cn.elricyu.tt.ui.MainFrame;

/**
 * 
 * @author elricyu
 */
public class TextAppender extends AppenderSkeleton {
	private Display display;
	private Text textArea;
	private static TextAppender appender = null;
	private boolean scroll = true;

	private TextAppender(Display display) {
		this.display = display;
	}

	public static TextAppender getInstance(Display display) {
		if (appender == null) {
			synchronized (TextAppender.class) {
				if (appender == null) {
					appender = new TextAppender(display);
					PatternLayout pl = new PatternLayout("%d{HH:mm:ss}: %m%n");
					appender.setLayout(pl);
					appender.setThreshold(Level.INFO);
				}
			}
		}
		return appender;
	}

	public Text getTextArea() {
		return textArea;
	}

	public void setTextArea(Text textArea) {
		this.textArea = textArea;
	}

	public void setDisplay(Display display) {
		this.display = display;
	}

	public void changeCurrentUser() {
		if (MainFrame.currentUser != null) {
			textArea.setText(SystemContainer.getLog(MainFrame.currentUser
					.getKey()));
			textArea.setSelection(Integer.MAX_VALUE, Integer.MAX_VALUE);
		}
	}

	public static Appender getAppender(String appenderName) {
		return getAppender(appenderName, null);
	}

	public static Appender getAppender(String appenderName, String categoryName) {
		Appender result = null;
		Logger logger;
		if (categoryName != null) {
			logger = Logger.getLogger(categoryName);
			if (logger != null) {
				result = logger.getAppender(appenderName);
			}
		}
		if (result == null) {
			logger = Logger.getRootLogger();
			result = logger.getAppender(appenderName);
		}
		return result;
	}

	@Override
	protected void append(LoggingEvent event) {
		final String text = this.layout.format(event);
		if (textArea == null || textArea.isDisposed() || display == null) {
			return;
		}

		if (CurrentContext.getUser() != null) {
			User user = CurrentContext.getUser();
			if (MainFrame.currentUser != null
					&& MainFrame.currentUser.getKey().equals(user.getKey())) {
				display.syncExec(new Runnable() {
					public void run() {
						if (textArea == null || textArea.isDisposed()) {
							return;
						}
						textArea.append(text);
					}
				});
			}
			SystemContainer.appendLog(CurrentContext.getUser().getKey(), text);
		}
	}

	@Override
	public void close() {
		if (textArea == null || textArea.isDisposed() || display == null) {
			return;
		}
		this.textArea.setText("");
	}

	public boolean requiresLayout() {
		return true;
	}
}
